import { constantRouterMap, _import } from '@/router'
import * as ResourceAPI from '@/api/resource'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles 当前的权限是admin 还是其他用户
 * @param route
 */
function hasPermission(roles, route) {
  if (route && route.subjectRoles) {
    return roles.some(role => route.subjectRoles.includes(role))
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles 当前的权限是admin 还是其他用户
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  const res = []
  asyncRouterMap.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, roles)
      }
      if (tmp.path) {
        res.push({
          path: tmp.path,
          component: _import(String(tmp.component).toLocaleLowerCase() === 'layout' ? 'layout/Layout' : tmp.component ? tmp.component : 'layout/Layout'),
          alwaysShow: false,
          name: tmp.name,
          meta: {
            title: tmp.name,
            icon: tmp.icon,
            roles: tmp.subjectRoles
          },
          children: tmp.children
        })
      }

      if (String(tmp.path).toLocaleLowerCase() === '/hide/menu') {
        res.pop()
      }
    }
  })
  return res
}

const permission = {
  state: {
    routers: [],
    addRouters: [],
    buttonRoles: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise((resolve, reject) => {
        const { roles } = data
        let accessedRouters
        ResourceAPI.getTreeMenu().then(response => {
          if (!response.data.data) {
            reject('error')
          }
          accessedRouters = filterAsyncRouter(response.data.data.children, roles)
          commit('SET_ROUTERS', accessedRouters)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default permission
